import { request } from '../../request/index.js'
import { getLocation } from '../../utils/asyncWx.js'

//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    //首页轮播图数组
    background: [],
    indicatorDots: true,
    vertical: false,
    autoplay: false,
    circular: false,
    interval: 2000,
    duration: 500,
    previousMargin: 0,
    nextMargin: 0,
    //首页二维码显隐  默认隐藏
    showApp: true,
    //轮播图圆点索引
    index: 0,
    active: 1,
    //生鲜水果商品分类
    freshClass: [],
    //推荐商品数组
    giveGoodsList: [],
    //社区数组
    communityList: [],
    //团长数组
    groupList: [
      // {
      //   id: 1,
      //   value: '富力城',
      //   isActive: false
      // },
      // {
      //   id: 2,
      //   value: '大宅城',
      //   isActive: false
      // },
      // {
      //   id: 3,
      //   value: '好多城啊啊啊啊啊啊啊',
      //   isActive: false
      // },
      // {
      //   id: 4,
      //   value: '西安城',
      //   isActive: false
      // }
    ],
    //获取到的主题
    themeList: [],
    //动画数据
    animationData: {},
    //控制下拉菜单的动画
    show: false,
    //选好的社区和团长  传递给头部组件
    communityObj: {
      communityName: '航开路',
      groupName: '富力城',
      detail: '航天大道118号紫园4-104、4-105',
      groupLeader: 1
    },
    QueryParams: {
      longitude: "",
      latitude: ""
    }

  },

  async onShow(options) {
    // let { communityObj } = this.data
    // const address = wx.getStorageSync("address");
    // if (address) {
    //   this.setData({
    //     communityObj: address
    //   })
    // } else {
    //   wx.setStorageSync("address", communityObj);
    // }
    const res = await getLocation()
    let { QueryParams } = this.data
    QueryParams.longitude = res.longitude
    QueryParams.latitude = res.latitude
    this.setData({
      QueryParams
    })
    //console.log(res)
    this.getCommunity()
    this.getBannerList()
    this.getTheme()
    const goodsTheme = 2
    const res1 = await request({ url: '/fresh/goods/showList', data: { goodsTheme } })
    this.setData({
      giveGoodsList: res1.data.data
    })
  },
  //跳转到生鲜水果分类页面
  handleGoFruitCategory() {
    wx.navigateTo({
      url: '../search/index'
    });
  },
  //控制首页二维码显隐
  handleShow() {
    let { showApp } = this.data
    showApp = !showApp
    this.setData({
      showApp
    })
  },
  //轮播图切换事件
  indexChange(e) {
    this.setData({
      index: e.detail.current
    })
  },
  //跳转到水果页面
  handleGoFruit(e) {
    console.log(e)
    const { classifyname, classifyid } = e.currentTarget.dataset
    const classifyName = classifyname
    const classifyId = classifyid
    wx.navigateTo({
      url: '../category/index?category=' + classifyName + '&classifyId=' + classifyId
    });
  },
  //跳转到水果商品详情页面
  handleGoFood(e) {
    const goodsId = e.currentTarget.dataset.goodsid
    wx.navigateTo({
      url: '../food/index?goodsId=' + goodsId
    });

  },
  /**
   * 点击定位
   */
  handleLocation() {
    let { show } = this.data
    this.setData({
      show: !show
    })
  },
  //点击选择团长
  chooseGroup(e) {
    const { index } = e.currentTarget.dataset
    let { groupList, show, communityObj } = this.data
    groupList.forEach((v, i) => i === index ? v.isActive = true : v.isActive = false)
    let i = groupList.findIndex(v => v.isActive === true)
    communityObj.groupName = groupList[i].groupLeaderName
    wx.setStorageSync("communityObj", communityObj);
    this.setData({
      groupList,
      show: !show,
      communityObj
    })
  },
  //点击选择社区
  async chooseCommunity(e) {
    const { index } = e.currentTarget.dataset
    let { communityList, communityObj, groupList } = this.data
    communityList.forEach((v, i) => i === index ? v.isActive = true : v.isActive = false)
    let i = communityList.findIndex(v => v.isActive === true)
    communityObj.communityName = communityList[i].communityName
    communityObj.communityId = communityList[i].communityId
    const community = communityList[i].communityId
    const res = await request({ url: '/community/groupLeader/selectList', data: { community } })
    this.setData({
      communityList,
      communityObj,
      groupList: res.data
    })
  },
  async onChange(event) {
    // wx.showToast({
    //   title: `切换到标签 ${event.detail.name}`,
    //   icon: 'none',
    // });
    console.log(event.detail.title)
    //const goodsTheme = event.detail.title
    const goodsTheme = event.detail.index + 1
    const res = await request({ url: '/fresh/goods/showList', data: { goodsTheme } })
    this.setData({
      giveGoodsList: res.data.data
    })
    console.log(this.data.giveGoodsList)
  },
  //获取商品主题
  async getTheme() {
    const res = await request({ url: '/fresh/goods/theme/showList' })
    this.setData({
      themeList: res.data
    })
    console.log(this.data.themeList)
  },
  //获取首页生鲜商品分类数据
  async getFreshClass() {
    const res = await request({ url: '/fresh/goods/classify/home' })
    this.setData({
      freshClass: res.data
    })
    //console.log(this.data.freshClass)
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    this.getFreshClass()
  },
  //获取轮播图数组
  async getBannerList() {
    const token = wx.getStorageSync("token");
    const header = { token }
    const bannerType = 1
    const res = await request({ url: "/banner/" + bannerType, data: { bannerType }, header })
    console.log(res)
    this.setData({
      background: res.data
    })
  },
  //获取社区数组
  async getCommunity() {
    const { QueryParams, communityObj } = this.data
    const res = await request({ url: '/community/selectList', data: QueryParams })
    communityObj.communityName = res.data[0].communityName
    communityObj.communityId = res.data[0].communityId
    this.setData({
      communityList: res.data,
      communityObj
    })
    this.getGroupList()
  },
  //获取团长数组
  async getGroupList() {
    const { communityList, communityObj } = this.data
    const community = communityList[0].communityId
    const res = await request({ url: '/community/groupLeader/selectList', data: { community } })
    communityObj.groupName = res.data[0].groupLeaderName
    communityObj.groupLeader = res.data[0].groupLeaderId
    communityObj.detail = res.data[0].groupLeaderAddressDetails
    communityObj.groupLeaderContactNumber = res.data[0].groupLeaderContactNumber
    //要的是addressId
    communityObj.address = ''
    this.setData({
      groupList: res.data,
      communityObj
    })
    //console.log(res.data)
    //console.log(this.data.communityObj)
    wx.setStorageSync("communityObj", communityObj);

  },
  getUserInfo: function (e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  //加入购物车
  handleCartClick(e) {
    const goodsId = e.currentTarget.dataset.id
    const { giveGoodsList } = this.data
    const goodsIndex = giveGoodsList.findIndex(v => v.goodsId === goodsId)
    const goodsObj = giveGoodsList[goodsIndex]
    const item = {
      id: parseInt(goodsObj.goodsId),
      recommended: goodsObj.goodsPick ? 'recommended' : '',
      thumb: 'https://ma.yzlsoft.cn/static/' + goodsObj.goodsPictureMain,
      price: goodsObj.goodsPriceDiscount,
      originPrice: goodsObj.goodsPriceOriginal,
      volume: goodsObj.goodsSalesVolume,
      extra: '特价 限1份',
      num: goodsObj.goodsSalesVolume,
      title: goodsObj.goodsName,
      desc: goodsObj.goodsSummary
    }
    this.cart.addToCart(item)
  },
  //去支付
  handlePay() {
    const token = wx.getStorageSync("token");
    if (!token) {
      wx.navigateTo({
        url: '../login/index'
      })
    } else {
      wx.navigateTo({
        url: '../confirm-order/index'
      })
    }
  },
  /**
 * 生命周期函数--监听页面初次渲染完成
 */
  onReady: function () {
    this.cart = this.selectComponent('#cart')
  },
})